package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.CountDownLatch;

public class RedisRealtimeBackup {
    public static void main(String[] args) {
        Jedis jedisMain = new Jedis("127.0.0.1", 6379);
        Jedis jedisBackup = new Jedis("localhost", 6379);//6380

        jedisMain.select(0);
        jedisBackup.select(1);

        // 订阅主 Redis 的键空间通知（包括 set 操作）
        jedisMain.psubscribe(new JedisPubSub() {
            @Override
            public void onPMessage(String pattern, String channel, String message) {
                System.out.println("Received message: " + message);
                System.out.println("Received channel: " + channel);

                if (channel.equals("__keyspace@0__:del")) {
                    // 监听到键被删除的事件，执行恢复操作
                    String deletedKey = message.split(":")[1]; // 获取被删除的键名
                    String valueToRestore = jedisBackup.get(deletedKey);
                    System.out.println("删除：" + valueToRestore);
                    if (valueToRestore != null) {
                        jedisMain.set(deletedKey, valueToRestore); // 从备用 Redis 恢复到主 Redis
                        System.out.println("Key '" + deletedKey + "' has been restored.");
                    }
                } else if (channel.equals("__keyspace@0__:set")) {
                    // 监听到键被设置的事件，执行备份操作
                    String addedKey = message.split(":")[1]; // 获取新增的键名
                    String valueToBackup = jedisMain.get(addedKey); // 从主 Redis 获取值

                    System.out.println("删除：" + valueToBackup);

                    if (valueToBackup != null) {
                        jedisBackup.set(addedKey, valueToBackup); // 备份到备用 Redis
                        System.out.println("Key '" + addedKey + "' has been backed up.");
                    }
                }
            }

            @Override
            public void onPSubscribe(String pattern, int subscribedChannels) {
                System.out.println("成功订阅模式：" + pattern);
            }

            @Override
            public void onPUnsubscribe(String pattern, int unsubscribedChannels) {
                System.out.println("取消订阅模式：" + pattern);
            }

            @Override
            public void onSubscribe(String channel, int subscribedChannels) {
                System.out.println("成功订阅频道：" + channel);
            }

            @Override
            public void onUnsubscribe(String channel, int unsubscribedChannels) {
                System.out.println("取消订阅频道：" + channel);
            }
        }, "__key*__:*");//__key*__:*
        //"__keyevent@0__:set", "__keyevent@0__:del"

        // 程序持续监听键空间变化
//        while (true) {
//            // 保持程序运行
//        }
        CountDownLatch latch = new CountDownLatch(1);
        try {
            latch.await(); // 等待计数器归零
        } catch (InterruptedException e) {
            // 处理中断异常
        }
    }
}